package auctionhaus

import com.auctionhaus.Bid
import com.auctionhaus.Customer
import com.auctionhaus.Listing
import grails.converters.*
import java.text.SimpleDateFormat
import org.springframework.mail.SimpleMailMessage.*
//import com.icegreen.greenmail.util.GreenMail
import org.springframework.mail.MailMessage.*

class BidService {
    static expose=['xfire']
    static transactional = true

    def mailService

    def placeBidOnListing(String listName, String buyerEmailAddress, String buyerPassword, Double amount) {
        def bid = null
        def listing = Listing.findByListName(listName)
        def buyer = Customer.findByEmailAddressIlike(buyerEmailAddress)
        if (listing && buyer && buyer.password == buyerPassword && amount.toString().number) {
            if (listing.endDateTime > new Date())
                bid = new Bid(amount:amount, date:new Date(), buyer:buyer, listing:listing).save(flush:true)

            if (bid) {
               // Req C1: Send Bid Confirmation Email stating successful bid
              try{
                    mailService.sendMail {
                        to  buyerEmailAddress
                        from 'ganzhullauctionhaus@gmail.com'
                        subject "Successful Bid Placed"
                        body "Congratulations ${buyerEmailAddress}, you have successfully placed a bid in the amount of ${amount} on listing ${listName}."
                    }
                     println "Confirmation email sent to ${buyerEmailAddress}"
               }catch(Exception e) {
                    println "Problem sending email ${e.message}"
               }

            }
        }
        return bid

    }
}
